package cn.net.zhenchan.common;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class MD5Utils {
	public static String code(String str)
	{
		try
		{
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte[] byteDigest = md.digest();
			int i;
			StringBuffer buf = new StringBuffer("");
			for (int offset = 0; offset < byteDigest.length; offset++)
			{
				i = byteDigest[offset];
				if (i < 0)
					i += 256;
				if (i < 16)
					buf.append("0");
				buf.append(Integer.toHexString(i));
			}
			// 32浣嶅姞瀵�
			return buf.toString();
			// 16浣嶇殑鍔犲瘑
			// return buf.toString().substring(8, 24);
		}
		catch (NoSuchAlgorithmException e)
		{
			e.printStackTrace();
			return null;
		}

	}

	public static String MD5PlusDate(String s)
	{
		String md5 = null;
		String serializeDate = DateUtils.formatSerializeDate();
		md5 = serializeDate + "_" + MD5(s);
		return md5;
	}

	public final static String MD5(String s)
	{
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try
		{
			byte[] btInput = s.getBytes();
			// 鑾峰緱MD5鎽樿绠楁硶鐨� MessageDigest 瀵硅薄
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 浣跨敤鎸囧畾鐨勫瓧鑺傛洿鏂版憳瑕�
			mdInst.update(btInput);
			// 鑾峰緱瀵嗘枃
			byte[] md = mdInst.digest();
			// 鎶婂瘑鏂囪浆鎹㈡垚鍗佸叚杩涘埗鐨勫瓧绗︿覆褰㈠紡
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++)
			{
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str).toLowerCase();
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public final static String createKey()
	{
		String nowTime = DateUtils.nowTime(DateUtils.Formats.YEAR_MOUTH_DAY);
		return MD5(nowTime + "huayuan");
	}

	public final static boolean isSame(String md5)
	{
		if (md5 != null && md5.equals(createKey()))
			return true;
		return false;
	}

	public static void main(String[] args)
	{
		// System.out.println(createKey());
		System.out.println(MD5("qqqqqq123").toLowerCase());
		System.out.println(MD5("justin123").toLowerCase());
		System.out.println(MD5("lijian123").toLowerCase());
	}
}
